package com.tao.controller;

import com.tao.config.MyLog;
import com.tao.mapper.MenuMapper;
import com.tao.pojo.User;
import com.tao.pojo.vo.ResponseResult;
import com.tao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin")
public class CmsAdminController {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private UserService userService;


    @MyLog("管理员列表")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/list")
    public Object list(@RequestBody User admin) {
        List<User> admins = menuMapper.selectAdminById(1L);

        if (!ObjectUtils.isEmpty(admin.getUsername())) {
            String targetUsername = admin.getUsername();
            List<User> filteredAdmins = admins.stream()
                    .filter(item -> item.getUsername().contains(targetUsername))
                    .collect(Collectors.toList());
            return ResponseResult.success(filteredAdmins);
        } else {
            return ResponseResult.success(admins);
        }
    }


    @MyLog("管理员编辑")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/edit")
    public Object edit(@RequestBody User admin){
        return userService.edit(admin);
    }

    @MyLog("管理员删除")
    @PreAuthorize("hasAnyAuthority('remove')")
    @PostMapping("/remove")
    public Object remove(@RequestBody User user){
        if (user.getId()==1){
            return ResponseResult.error("admin管理员不可删除!");
        }
        userService.removeById(user);
        return ResponseResult.success(null);
    }
}
